package com.client.util;

import com.common.entity.RPCResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Zixiang Hu
 * @description 在高并发情况下，将请求以键值的形式存在在该类中，完成请求后将请求删除
 * @create 2021-03-04-16:01
 */
@Slf4j
public class UnProcessRequests {
    // 这里使用并发map，因为hashmap在高并发下是线程不安全的
    private static final ConcurrentHashMap<String, CompletableFuture<RPCResponse>> UNPROCESS_HASH_MAP = new ConcurrentHashMap<>();

    public void put(String requestId, CompletableFuture<RPCResponse> completableFuture) {
        UNPROCESS_HASH_MAP.put(requestId, completableFuture);
    }

    public CompletableFuture<RPCResponse> remove(String requestId) {
        return UNPROCESS_HASH_MAP.remove(requestId);
    }

    public void completeRequest(RPCResponse response) {
        if (response == null || response.getRequestId().length() == 0) {
            log.error("requestId不能为空");
            return;
        }
        CompletableFuture<RPCResponse> completableFuture = remove(response.getRequestId());
        if (completableFuture != null) {
            completableFuture.complete(response);
        }else {
            log.error("UnProcessRequests的completeRequest发生异常，completableFuture为空");
        }
    }
}
